<?php

namespace catchAdmin\externalGoods\service;

use catchAdmin\customs\model\HnOrderDetail;
use catchAdmin\customs\model\Order;
use catchAdmin\customs\model\OrderSon;
use catchAdmin\externalGoods\model\Category;
use catchAdmin\externalGoods\model\GoodsAttribute;
use catchAdmin\externalGoods\model\GoodsRule;
use catchAdmin\externalGoods\model\OrderLogistics;
use think\facade\Request;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use houniao\api\v1\Goods;
use think\Exception;
use think\facade\Db;
use xyb2b\api\v1\Link;

class XyGoodsService{

    protected $user;
    protected $price_fl = 1.1;
    protected $supplier_id = 3;
    protected $freight = 5;

    protected $tenantList =  [
        ['tenant_id'=>'10043'],
        ['tenant_id'=>'10050'],
        ['tenant_id'=>'10144'],
        ['tenant_id'=>'10146'],
        ['tenant_id'=>'10147'],
        ['tenant_id'=>'10159'],//果然便宜
        ['tenant_id'=>'10161']//文商跨境
    ];

    public static $trade_type_option = [
        1 => "保税直供",
        2 => "完税进口",
        3 => "国内贸易",
        4 => "香港直邮",
        5 => "海外直邮",
    ];

    public static $to_trade_tyep_option = [
        1 => 4,
        2 => 1,
        4 => 2,
        5 => 3
    ];

    public static $spec_convert = [
        0 => 1,
        1 => 2
    ];

    //价格&库存通知
    public function sku_price_notice_v2($full_data)
    {
//        dd($full_data);
        $xy_data = $full_data['result_content'];
        $notice_type = $xy_data['notice_type'];
        $sku_id = $xy_data['sku_id'];

        $xyb2b = new Link();

        //商品详情
        $goodsDetail = $xyb2b->get_product_detail_v2([
            'sku_id_list'=>[$sku_id]
        ])['list'];
        if(!empty($goodsDetail)){
            $goodsDetail = $goodsDetail[0];
        }

        $xyGoodsService = $this;
        //$formatData = $xyGoodsService->goodsSkuSave($data);

        $goodsInfo = (new GoodsRule)->where(['goods_sku'=>$sku_id])->find();
        $goodsModel = new externalGoodsModel;
        $goodsAttrModel = new GoodsAttribute;
        $goodsRuleModel = new GoodsRule;
        if ('处理成功' == $full_data['ret_msg']) {//成功
//            变动类型 1.价格变动通知(批次上下架导致价格变动) 2.有货通知 3.无货通知 4.上架通知 5.下架通知 8.商品信息变更通知
            if(in_array($notice_type,[1,2,4,8])){
                $xyGoodsService->goodsSkuSave($goodsDetail);
                //$goodsInfo && $this->updateGoodsBySupplier($goodsInfo['goods_id'],$goodsInfo['goods_spu']);
            }

            if($goodsInfo && in_array($notice_type,[3,5])){//无货通知 & 下架商品 并且存在sku
                /****
                //删除规格
                $goodsRuleModel::destroy(function($query) use ($goodsInfo,$sku_id){
                    $query->where('goods_spu', $goodsInfo['goods_spu'])
                        ->where('goods_sku', $sku_id);
                },true);
                //删除属性
                $goodsAttrModel::destroy(function($query) use ($goodsInfo,$sku_id){
                    $query->where('goods_spu', $goodsInfo['goods_spu'])
                        ->where('name', '发货仓库')
                        ->where('attribute_name', $sku_id);
                },true);

                 *
                 */

                //库存，改成0
                $goodsInfo->sku_stock= 0;
                $goodsInfo->save();

                //更新商品价格和库存
                $allRuleResult = $goodsRuleModel->where(['goods_id'=>$goodsInfo['goods_id']])->select()->toArray();
                $minSkuPrice = min(array_column($allRuleResult,'sku_price'));
                $minCostPrice = min(array_column($allRuleResult,'cost_price'));
                $allStockNum = array_sum(array_column($allRuleResult,'sku_stock'));
                $goodsModel->updateBy($goodsInfo['goods_id'],['cost_price'=>$minCostPrice,'price'=>$minSkuPrice,'stock'=>$allStockNum]);

                //更新供应商商品
                $this->updateGoodsBySupplier($goodsInfo['goods_id'],$goodsInfo['goods_spu']);
            }
        }
        return ['status'=>1, 'msg'=>'success'];
    }


    //行云物流单号保存
    public function logisticsFormart($order_no, $apiData){
        $return = [];
        $hnOrderModel = new HnOrderDetail;
        foreach ($apiData['express_list'] as $d){
            $hnInfo = $hnOrderModel->where('order_no',$order_no)->find();

            $_data = [
                'order_id'=> $hnInfo['source_order_no'],
                'main_order_id'=> $hnInfo['main_order_id'],
                'order_no'=> $hnInfo['order_no'],
                'express_no'=> $d['express_order'],
                'express_name'=> $d['express_company'],
                'express_code'=> '',
                'delivery_time'=> date("Y-m-d H:i:s",time()),
                'supplier_id'=> 3
            ];

            $return[] = $_data;
        }

        return $return;
    }

    //订单发货通知
    public function deliver_order_notice_v2($full_data)
    {
        $xy_data = $full_data['result_content'];

//        $xy_data['order_id'] = 'O1000002799564';

        if ('处理成功' == $full_data['ret_msg']) {//成功
            $logisticsModel = new OrderLogistics;
            $order_no = $xy_data['order_id'];
            $logisticsFind = $logisticsModel->where('order_no',$order_no)->find();

            if($logisticsFind){
                return ['status'=>1, 'msg'=>'success'];
            }

            $return = [];
            $hnOrderDetailModel = new HnOrderDetail;
            $orderSonModel = new OrderSon;

            $hnInfo = $hnOrderDetailModel->where('order_no',$order_no)->find();
            $supplier_id = $orderSonModel->where('orderlistId',$hnInfo['source_order_no'])->value('goods_supplier_id');

            foreach ($xy_data['express_list'] as $d){
                $_data = [
                    'order_id'=> $hnInfo['source_order_no'],
                    'main_order_id'=> $hnInfo['main_order_id'],
                    'order_no'=> $hnInfo['order_no'],
                    'express_no'=> $d['express_order'],
                    'express_name'=> $d['express_company'],
                    'express_code'=> '',
                    'delivery_time'=> date("Y-m-d H:i:s",time()),
                    'supplier_id'=> $supplier_id
                ];

                $return[] = $_data;
            }

            foreach ($return as $__d){
                $logisticsModel->createBy($__d);
            }

            //更改订单状态
            $order_status = 1;
            $mall_order_status = 1;
            $save = [
                'order_status'=>$order_status,
                'mall_order_status'=>$mall_order_status,
                'sync_api_data_time'=>time() + mt_rand(1,10000)
            ];


            //保存主订单订单状态信息
            $orderStatusOptions = [
                -3=>'异常订单',
                -2=>'是待付款',
                -1=>'已取消',
                0=>'待发货',
                1=>'已发货',
                2=>'已收货',
                3=>'海关审核中|仓库分拣打包中',
                5=>'已完成',
            ];
            $push_status = array_key_exists($mall_order_status,$orderStatusOptions) ? $orderStatusOptions[$mall_order_status] : '未知';

            $orderModel = new \catchAdmin\api\model\Order;
            $orderModel = $orderModel->where('orderId',$hnInfo['main_order_id'])->find();

//            if($orderModel->push_status != '已取消'){
                $orderModel->push_status = $push_status;
                $orderModel->save();
//            }

            $res =  $hnInfo->save($save);
        }

        return ['status'=>1, 'msg'=>'success'];
    }

    //保税订单清关状态通知
    //{"notice_code":"order_customs_clearance_notice_v2","sign":"233b06d748d67cad69ef8eb88f1e1fb2","result_content":{"customs_clearance_status":100,"customs_clearance_time":1733378489675,"merchant_order_id":"123233412335533_1","order_id":"O1000002799564"},"merchant_id":"2024112997124650","ret_msg":"处理成功","business_id":"af88a322-4c3e-49ba-b682-3504266330e0","ret_code":"200","sign_type":"MD5","version":"2"}
    public function order_customs_clearance_notice_v2(){
        return ['status'=>1, 'msg'=>'success'];
    }

    //处理订单生成
    public function generate_order_notice_v2($full_data){
        $xy_data = $full_data['result_content'];
        $apiOrderSonModel = new HnOrderDetail;

        $orderlist_pk = (new OrderSon)->where(['orderlistId'=>$xy_data['merchant_order_id']])->value('id');

        $orderSonResult = (new OrderSon)->findBy($orderlist_pk);

        if($orderSonResult['api_post_status'] == 1 && !empty($orderSonResult['api_return'])){ //子订单提示已经处理
            return ['status'=>1, 'msg'=>'success'];
        }

        $orderResult = (new Order)->where('orderId',$orderSonResult['orderId'])->find();
        $order_pk = $orderResult['id'];

//        dd($order_pk);

        $tenant_id =$orderResult->tenant_id;

        if(1 == $xy_data['is_success']){//成功

            //子订单数据
            $apiOrderListData = $xy_data['order_list'];

            $orderDetailArr = [];
            foreach ($apiOrderListData as &$value) {
                $ord = [];
                $ord['order_id'] = $order_pk;
                $ord['order_no'] = $value['child_order_id'];

                $findTableData = $apiOrderSonModel->where(['order_no'=>$ord['order_no']]);
                if(!$findTableData) continue;

                $ord['main_order_id'] = $orderSonResult['orderId'];
                $ord['source_order_no'] = $orderSonResult['orderlistId'];
                $ord['tenant_id'] = $tenant_id;
                //$ord['creator_id'] = $creator_id;

                $_orderGoods = $value['sku_list'][0];

                $goods_rule_info = (new GoodsRule())->where(['goods_sku'=>(string) $_orderGoods['sku_id']])->find();
                $goods_spu =  $goods_rule_info['goods_spu'];

                $ord['goods_spu'] = $goods_spu;
                $ord['goods_sku'] =  $_orderGoods['sku_id'];
                $ord['sku_id'] =  $_orderGoods['sku_id'];

//                //打一个布丁，因为接口没有商品单价，所以这里重新计算一下
//                if((int) $value['product_num'] > 1 ){//购买多件
//                    $value['product_price'] = bcdiv($value['product_price'],$value['product_num'],2);
//                }

                $ord['deliver_money'] = $value['freight_amount'];//运费
                $ord['tax_difference_money'] = $value['tax_difference'];//税差金额
                $ord['sku_tax_amount'] = $_orderGoods['sku_tax_amount'];//综合税费
                $ord['sku_tax_rate'] = $_orderGoods['sku_tax_rate'];//综合费率
                $ord['goods_price'] = $_orderGoods['sku_price'];//商品成本单价
                $ord['goods_money'] = $_orderGoods['sku_price'] * $_orderGoods['buy_num'];//商品成本总价
                $ord['total_money'] = $value['pay_amount'] ;//订单商品 总金额（商品总价+其他例如运费）
                $ord['real_total_money'] = $value['pay_amount']; //实际支付金额 如果有优惠
                $ord['goods_num'] = $_orderGoods['buy_num'];//商品数量
                $ord['goods_name'] = (new externalGoodsModel)->where('goods_spu', $goods_spu)->value('goods_name');

                if($tenant_id !== 0){
                    $user = (new \catchAdmin\permissions\model\Users())->find($tenant_id);
                }

                $percent = (float) $user['qekj_tenant_goods_precent'];

                //涉及到 邮费+税费 所以直接获取成本价（已经包含过的）
                $ord['tenant_goods_price'] = round( $goods_rule_info['cost_price'] * $percent);

                //渠道商商品总额
                $ord['tenant_goods_money'] = $ord['tenant_goods_price'] * $ord['goods_num'];//渠道商商品总价
                //渠道商 结算价格    ===  商品总额 + 运费 + 税差 - 优惠
                //$ord['tenant_total_money'] = $ord['tenant_goods_money'] + $value['deliver_money'] + $value['tax_difference_money'] - $value['deliver_money'];
                $ord['tenant_total_money'] = $ord['tenant_goods_price'] * $ord['goods_num'];//渠道商订单总金额

                $orderDetailArr[] = $ord;
            }

//            dd($orderDetailArr);

            $orderResult->push_status = '待发货';
//        $orderResult->order_items = $data;//返回的api数据
            $res1 =  $orderResult->save();
            //推送后，创建明细单
            $res2 = $apiOrderSonModel->saveAll($orderDetailArr);

            $orderSonResult->api_return = $full_data;
            $orderSonResult->api_error = NULL;
            $orderSonResult->api_post_status = 1;
            $res3 = $orderSonResult->save();

            if(!$res1 || !$res2 || !$res3){
                return ['status'=>0, 'msg'=>'订单数据保存失败'];
            }

            return ['status'=>1, 'msg'=>'success'];
        }elseif (2 == $xy_data['is_success']){//失败
            $orderResult->push_status = '处理失败';
            $orderResult->save();

            $orderSonResult->api_return = $full_data;

            $orderSonResult->api_error = [$full_data['ret_msg']];
            $orderSonResult->api_post_status = -1;
            $res3 = $orderSonResult->save();
            return ['status'=>1, 'msg'=>'success'];
        }
    }

    //行云货品
    public function goodsSkuSave(&$data){
        $cateModel = new Category;
        $price = 0;

        $format = [];
        $format['ext_id'] = $data['product_code'];
        $format['goods_spu'] = 'XYG' .  $data['product_code'];
//        $format['goods_spu'] = 'XYNO' .  $data['product_code'];
        $format['goods_name'] = $data['product_name'];
        $format['goods_img'] = $data['sku_img'];

        $format['goods_slideshow_img'] =  json_encode(array_slice($data['sku_thumb_image'] ,  1) ?: [] , JSON_UNESCAPED_UNICODE);

        $format['barcode'] = '';//商品编码
        $format['weight'] = $data['package_weight'] ?? '';//商品重量
        $format['brand_id'] = $data['brand_id'];
        $format['brand_name'] = $data['brand_name'];
        $format['sync_brand_id'] = $data['brand_id'];
        $format['sync_brand_name'] = $data['brand_name'];

        $format['origin_name'] = $data['origin_name'] ?? '';
        $format['trade_type_id'] = self::$to_trade_tyep_option[$data['trade_type']];
        $format['trade_type_name'] = self::$trade_type_option[$format['trade_type_id']] ;
        $format['unit_name'] = $data['measure_spec'];

        $format['is_sale'] = (int) $data['on_sales'];

        $format['sync_category_id'] =  $data['category_id3'] ?? $data['category_id2'] ?? $data['category_id1'];  //api传输的cate_id
        $format['category_id'] =  $cateModel->where('xy_cate_id',$format['sync_category_id'])->value('id'); //查询的
        $format['sync_category_id_path'] = "{$data['category_id1']}_{$data['category_id2']}_{$data['category_id3']}";
        $format['sync_category_name'] = '';
        $format['supplier_id'] = $this->supplier_id;
        $format['spec'] = 2;
//        $format['market_price'] = 111;

        $price = $data['price_list'][0]['batch_sell_price'];
        $batch_package_num = $data['price_list'][0]['batch_package_num'];
        $batch_start_num = $data['price_list'][0]['batch_start_num'];//规格起发量

//        print_r('包装规格' . $data['price_list'][0]['batch_package_num'] . PHP_EOL);

        //判断是否需要税率
        if (isset($data['price_type']) && $data['price_type'] == '不含税') {
            $tax_rate = $data['price_list'][0]['tax_rate'];  // 税率

            // 计算含税价格
            $tax_multiplier = bcadd('1', (string)$tax_rate, 2);  // 计算 1 + 税率
            $final_price = bcmul((string)$price, $tax_multiplier, 2);  // 销售价格 * (1 + 税率)
            $price = $final_price;
        }

        //判断是否不包邮
        if (isset($data['model_type_name']) && $data['model_type_name'] == '不包邮') {
            $price = bcadd($price,$this->freight,2);
        }

        $format['description'] = $data['sku_detail'] ?? '';

        $goodsModel = new externalGoodsModel;
        $goodsAttrModel = new GoodsAttribute;
        $goodsRuleModel = new GoodsRule;

        //判断商品是否存在
        $findGoods = $goodsModel->where(['goods_spu'=>$format['goods_spu'],'supplier_id'=>$this->supplier_id])->find();
        if(!$findGoods){//添加商品
           $goods_pk =  $goodsModel->storeBy($format);
        }else{
            //判断商品的贸易类型是否发生了修改，如果修改了就抛出异常
            if($findGoods['trade_type_id'] != $format['trade_type_id']){
                throw new Exception('商品:' . $format['goods_spu'] . '贸易类型发生改变，暂不支持多贸易类型商品');
            }

            $goods_pk = $findGoods['id'];
            $goodsModel->updateBy($goods_pk,$format);
        }

        //添加修改属性
        $sku_attributes_id = [];
        $sku_attributes_value = [];
//        foreach ($data['sku_attributes'] as $key => $value){

        //将 重量：900g ;产品规格：4段 ; 重量：900g 隔开
        $sku_spec_value = explode(';',$data['sku_spec_value']);
        //去除最后一个元素
        $sku_spec_value = array_slice($sku_spec_value,0,-1);

        $sku_name_arr = [];

        foreach ($sku_spec_value as $key => $value){
            $attribute_arr = explode('：',$value);
            //把里面元素 空格去掉
            $attribute_arr = array_map('trim',$attribute_arr);

            $md5_attribute_id = md5($value .  $format['goods_spu']);

            $sku_attributes_value[] = $attribute_arr[1];

            $sku_name_arr[]  = $attribute_arr[0] . ':' . $attribute_arr[1];

            //拿仓库作为唯一标识符
            $findAttr =  $goodsAttrModel->where(['goods_spu'=>$format['goods_spu'],'attribute_id'=>$md5_attribute_id])->find();
            if(!$findAttr){
                $attrData = ['attribute_id'=>$md5_attribute_id,'name'=>$attribute_arr[0],'attribute_name'=>$attribute_arr[1],
                        'goods_id'=>$goods_pk,'goods_spu'=>$format['goods_spu'],'supplier_id'=>$this->supplier_id];
                $goodsAttrModel->insert($attrData);
                $sku_attributes_id[] = $md5_attribute_id;
            }else{
                $sku_attributes_id[] = $findAttr['attribute_id'];
            }

            if($key == count($sku_spec_value) - 1){
                //判断仓库是否保存过
                $md5_attribute_id2 = md5($value .  $format['goods_spu'] . $data['sku_id'] );
                $findAttr1 =  $goodsAttrModel->where(['goods_spu'=>$format['goods_spu'],'attribute_id'=>$md5_attribute_id2])->find();
                if(!$findAttr1){
                    $attrData1 =  ['attribute_id'=>$md5_attribute_id2,'name'=>'发货仓库','attribute_name'=>$data['sku_id'],
                        'goods_id'=>$goods_pk,'goods_spu'=>$format['goods_spu'],'supplier_id'=>$this->supplier_id];
                    $goodsAttrModel->insert($attrData1);
                    $sku_attributes_id[] = $md5_attribute_id2;
                }else{
                    $sku_attributes_id[] = $findAttr1['attribute_id'];
                }
                $sku_attributes_value[] = $data['sku_id'];
            }
        }
        //$data['sku_attributes'][] = "发货仓库:{$data['sku_id']}";
        $sku_name_arr[] = "发货仓库:{$data['sku_id']}";

        //dd($sku_attributes_id);

        $sku_price = round($price * $this->price_fl);

        //添加修改规格
        $findRule =  $goodsRuleModel->where(['goods_spu'=>$format['goods_spu'],'goods_sku'=>$data['sku_id']])->find();
        $ruleData = [
            'ext_id'=>$data['sku_id'],'goods_sku'=>$data['sku_id'],'goods_id'=>$goods_pk,'goods_spu'=>$format['goods_spu'],
            'spec_sku'=>implode('_',$sku_attributes_id),'sku_name'=>implode(';',$sku_name_arr),
            'sku_attribute_id'=>json_encode($sku_attributes_id,JSON_UNESCAPED_UNICODE),
            'sku_attribute_name'=>json_encode($sku_attributes_value,JSON_UNESCAPED_UNICODE),
            'sku_price'=>$sku_price,'cost_price'=> $price,'sku_weight' => $format['weight'],
            'sku_stock'=>$data['stock_num'],'sku_quantity'=>$batch_package_num,
            'supplier_id'=>$this->supplier_id
        ];

        //如果规格起发量大于1，设置库存为0
        if($batch_start_num > 1){
            $ruleData['sku_stock'] = 0;
            $ruleData['spec_img'] = 'spec_img';
        }

        if(!$findRule){
            $goodsRuleModel->storeBy($ruleData);
        }else{
            $goodsRuleModel->updateBy($findRule['id'],$ruleData);
        }

        //更新商品价格和库存
        $allRuleResult = $goodsRuleModel->where(['goods_id'=>$goods_pk])->select()->toArray();
        $minSkuPrice = min(array_column($allRuleResult,'sku_price'));
        $minCostPrice = min(array_column($allRuleResult,'cost_price'));
        $allStockNum = array_sum(array_column($allRuleResult,'sku_stock'));

        $goodsModel->updateBy($goods_pk,['cost_price'=>$minCostPrice,'price'=>$minSkuPrice,'stock'=>$allStockNum]);

        //更新供应商商品
        $this->updateGoodsBySupplier($goods_pk,$format['goods_spu']);

        return true;
    }

    //给所有供应商更新
    public function updateGoodsBySupplier($goods_id,$goods_spu){
        $list = $this->tenantList;
        $goodsService = new GoodsService;

        //给所有供应商更新
        foreach ($list as $value){
            $goodsService->delAndInsGoods($goods_id,$goods_spu,$value['tenant_id']);
        }
    }
}